//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using System;
using SR = Microsoft.Research.DataLayer;
using Microsoft.Research.ScientificWorkflow.TridentUtilities;

namespace Microsoft.Research.ScientificWorkflow.TridentComposer
{
    public class ImportTypeInitializerProxy : MarshalByRefObject
    {
        #region private fields
        private string typeInitializerAssemblyPath;
        private SR.Connection registryConnection;
        #endregion

        #region Constructors

        /// <summary>
        /// Dummy constructor to allow creation of object through CreateInstanceAndUnwrap API.
        /// </summary>
        public ImportTypeInitializerProxy()
        {
        }

        /// <summary>
        /// Initializes a new instance of the typeinitializer proxy.
        /// </summary>
        /// <param name="assemblyPath">The assembly path.</param>
        /// <param name="registryConnection">The registry connection.</param>
        public ImportTypeInitializerProxy(string assemblyPath, SR.Connection registryConnection)
        {
            this.typeInitializerAssemblyPath = assemblyPath;
            this.registryConnection = registryConnection;
        }
        #endregion

        #region Public methods
        /// <summary>
        /// Import the type initializers.
        /// </summary>
        /// <returns>True if the import was successful;False otherwise.</returns>
        public OperationStatus Execute()
        {
            AppDomain childAppdomain = null;
            try
            {
                childAppdomain = this.CreateAppDomain();
              
                ImportTypeInitializerProxy importProxy = childAppdomain.CreateInstanceAndUnwrap
                    ("Microsoft.Research.ScientificWorkflow.TridentComposer",
                    "Microsoft.Research.ScientificWorkflow.TridentComposer.ImportTypeInitializerProxy") as ImportTypeInitializerProxy;
                importProxy.Init(this.typeInitializerAssemblyPath, this.registryConnection);
                return importProxy.ImportTypeInitializer();
            }
            finally
            {
                UnloadAppDomain(childAppdomain);
            }
        }
        #endregion

        #region private methods
        /// <summary>
        /// Initialize the proxy object created in another appdomain.
        /// </summary>
        /// <param name="assemblyPath">The assembly path.</param>
        /// <param name="connection">The registry connection.</param>
        private void Init(string assemblyPath, SR.Connection connection)
        {
            this.typeInitializerAssemblyPath = assemblyPath;
            this.registryConnection = connection;

            SR.SR_Connection.Init();
            this.registryConnection.Open();
            this.registryConnection.AutoSave = false;

            // Authenticate the user.
            try
            {
                TridentAuthentication authenticate = new TridentAuthentication(this.registryConnection);
                authenticate.AuthenticateUser();
            }
            catch (TridentCustomException)
            {
                throw;
            }
        }

        /// <summary>
        /// Imports the type initializer.
        /// </summary>
        /// <returns>True if the import was successful;False otherwise.</returns>
        private OperationStatus ImportTypeInitializer()
        {
            ActivityComposer activityComposer = new ActivityComposer(this.registryConnection, false);
            return activityComposer.ImportCustomTypeInitializers(this.typeInitializerAssemblyPath);
        }

        /// <summary>
        /// Creates a new app domain.
        /// </summary>
        /// <returns>New instance of the app domain.</returns>
        private AppDomain CreateAppDomain()
        {
            AppDomain newDomain = AppDomain.CreateDomain("ImportTypeInitializerAppdomain");
            newDomain.UnhandledException += new UnhandledExceptionEventHandler(AppDomainUnhandledException);
            return newDomain;
        }

        /// <summary>
        /// Unloads the app domain.
        /// </summary>
        /// <param name="appDomain">Instance of the AppDomain.</param>
        private static void UnloadAppDomain(AppDomain appDomain)
        {
            if (appDomain != null)
            {
                AppDomain.Unload(appDomain);
            }
        }

        /// <summary>
        /// Method logs the unhandled exception in the app domain.
        /// </summary>
        /// <param name="sender">Object who raises the unhandled exception.</param>
        /// <param name="e">Event argument containing exception details.</param>
        private void AppDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            // No-op.
        }
        #endregion
    }
}
